import cookies from 'weapp-cookie'

function post(url,data,success,fail){
	
	let header = {
		"Content-Type":"application/json",
	};
	
	console.log(cookies);
	console.log('--> header:' + JSON.stringify(header));
	console.log('--> request sending... [' + url + '], data:' + JSON.stringify(data));
	
	uni.request({
		url: url,
		method: 'POST',
		header:header,
		data: data || {},
		success: res => {
			const data = res.data;
			console.log('--> response receiving... [' + url + '], data:' + JSON.stringify(data));
			switch(data.code){
				case 0:
					if (typeof success == 'function') {
						success(data);
					}
					break;
				case 401:
					reLogin();
					break;	
				default:
					if (typeof fail == 'function') {
						fail(data);
					}
					break;
			}
		},
		fail: (err) => {
			console.log('--> response receiving... [' + url + '], err:' + JSON.stringify(err));
			if (typeof fail == 'function') {
				fail({
					code:-1,
					msg:"请求失败"
				});
			}
		},
		complete: () => {
			
		}
	});
}

function upload(tfp, url, filename, data, success, fail) {
	const uploadTask = uni.uploadFile({
		url: url,
		filePath: tfp,
		name: filename,
		formData: data || {},
		success: res => {
			let data = res.data;
			if(typeof data == "string"){
				data = JSON.parse(data);
			}
			console.log('--> response receiving... [' + url + '], data:' + JSON.stringify(data));
			switch(data.code){
				case 0:
					if (typeof success == 'function') {
						success(data);
					}
					break;
				case 401:
					reLogin();
					break;	
				default:
					if (typeof fail == 'function') {
						fail(data);
					}
					break;
			}
		},
		fail: (err) => {
			console.log('--> response receiving... [' + url + '], err:' + JSON.stringify(err));
			if (typeof fail == 'function') {
				fail({
					code:-1,
					msg:"请求失败"
				});
			}
		},
		complete: () => {
			
		}
	})

	uploadTask.onProgressUpdate((res) => {
		console.log('上传进度', res.progress)
		console.log('已经上传的数据长度', res.totalBytesSent)
		console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend)
	})
}

function reLogin(){
	uni.reLaunch({
		url: '/pages/login/login',
	})
}

module.exports = {
	post,
	upload
}

